# from socket import *
#
# from multiprocessing import Process
# def run1():
#     s = socket(AF_INET,SOCK_DGRAM)
#     s.bind(("",60255))
#     # addr = ("192.168.31.181",8080)
#     # date = input("请输入要发送的内容：")
#     # s.sendto(date.encode("gb2312"),addr)
#     s.sendto("你好".encode("gb2312"),("192.168.31.181",8080))
# def run2():
#     s = socket(AF_INET, SOCK_DGRAM)
#     s.bind(("", 60255))
#     redate = s.recvfrom(1024)
#     print(redate[0].decode("gb2312"),redate[1])
#     # s.close()
# while True:
#     if __name__ == '__main__':
#         p=Process(target=run1)
#         p.start()
#         p.join()
#         p=Process(target=run2)
#         p.start()
#         p.join()

#
# from socket import *
#
# s = socket(AF_INET,SOCK_DGRAM)
# s.bind(("",60255))
# s.sendto("张飞".encode("gb2312"),("192.168.31.181",8080))
# redate = s.recvfrom(1024)
# print(redate[0].decode("gb2312"))


# echo
# from socket import *
#
# udpSock = socket(AF_INET,SOCK_DGRAM)
# udpSock.bind(("",60255))
# while True:
#
#     recvData = udpSock.recvfrom(1024)
#     udpSock.sendto(recvData[0],recvData[1])
# udpSock.close()


#TFTP 端口号69  实现TFTP下载器  （udp）
from socket import *
import struct
cmb_buf = struct.pack("!H7sb5sb",1,b"abc.png",0,b"cotet",0)
udpSock = socket(AF_INET,SOCK_DGRAM)
udpSock.sendto(cmb_buf,("192.168.31.181",69))
f = open("abc.png","ab")
# while True:
recv_data = udpSock.recvfrom(1024)
print(recv_data)
    caozuoma,ack_num = struct.unpack("!HH",recv_data[0][:4])
    rand_port = recv_data[1][1]
    if int(caozuoma) == 5:
        print("文件不存在")
        break
    # print("操作码：%d.ACK:%d,服务器随机端口：%d，数据长度：%d"%(caozuoma,ack_num,rand_port,))
    f.write(recv_data[0][4:])
    if len(recv_data[0])<516:
        break
    ack_data = struct.pack("!HH",4,ack_num)
    udpSock.sendto(ack_data, ("192.168.31.181", rand_port))